package com.mogujie.tt.ui.base;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextPaint;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mogujie.tools.ScreenTools;
import com.mogujie.tt.DB.sp.GesturespasswordSp;
import com.mogujie.tt.DB.sp.LoginSp;
import com.mogujie.tt.R;
import com.mogujie.tt.app.IMApplication;
import com.mogujie.tt.ui.activity.DigitalCodeActivity;
import com.mogujie.tt.ui.activity.GesturesActivity;
import com.mogujie.tt.ui.activity.SearchActivity;
import com.mogujie.tt.ui.activity.UnlockGesturePasswordActivity;
import com.mogujie.tt.ui.widget.AddPopWindow;
import com.mogujie.tt.utils.FileUtil;
import com.mogujie.tt.utils.Logger;
import com.mogujie.tt.ui.widget.SearchEditText;
import com.mogujie.tt.ui.widget.TopTabButton;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.File;

public abstract class TTBaseFragment extends Fragment {
	protected ImageView topLeftBtn;
	protected ImageView topRightBtn;
	protected TextView topTitleTxt;
	protected TextView topLetTitleTxt;
	protected TextView topRightTitleTxt;

	protected ViewGroup topBar;
	protected TopTabButton topContactTitle;
	protected SearchEditText topSearchEdt;
	protected ViewGroup topContentView;
	protected RelativeLayout topLeftContainerLayout;
	protected FrameLayout searchFrameLayout;
	protected FrameLayout topContactFrame;
	
	protected float x1, y1, x2, y2 = 0;
	protected static Logger logger = Logger.getLogger(TTBaseFragment.class);

	protected boolean isAutoPlay=false;
	protected boolean Num = false;
	protected boolean Ges = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		topContentView = (ViewGroup) LayoutInflater.from(getActivity()).inflate(R.layout.tt_fragment_base, null);

		topBar = (ViewGroup) topContentView.findViewById(R.id.topbar);
		topTitleTxt = (TextView) topContentView.findViewById(R.id.base_fragment_title);
		topLetTitleTxt = (TextView) topContentView.findViewById(R.id.left_txt);
		topRightTitleTxt = (TextView) topContentView.findViewById(R.id.right_txt);
		topLeftBtn = (ImageView) topContentView.findViewById(R.id.left_btn);
		topRightBtn = (ImageView) topContentView.findViewById(R.id.right_btn);
		topContactTitle = (TopTabButton) topContentView.findViewById(R.id.contact_tile);
		topSearchEdt = (SearchEditText) topContentView.findViewById(R.id.chat_title_search);//搜索框
		topLeftContainerLayout=(RelativeLayout)topContentView.findViewById(R.id.top_left_container);
		searchFrameLayout = (FrameLayout)topContentView.findViewById(R.id.searchbar);
		topContactFrame = (FrameLayout)topContentView.findViewById(R.id.contactTopBar);
				
		topTitleTxt.setVisibility(View.GONE);
		topRightBtn.setVisibility(View.GONE);
		topLeftBtn.setVisibility(View.GONE);
		topLetTitleTxt.setVisibility(View.GONE);
		topRightTitleTxt.setVisibility(View.GONE);
		topContactTitle.setVisibility(View.GONE);
		topSearchEdt.setVisibility(View.GONE);

			if(isPad()){
			getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//横屏
		}else{
			getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup vg,
			Bundle bundle) {
		if (null != topContentView) {
			((ViewGroup) topContentView.getParent()).removeView(topContentView);
			return topContentView;
		}
		return topContentView;
	}

	protected void setTopTitleBold(String title) {
		if (title == null) {
			return;
		}
		if (title.length() > 12) {
			title = title.substring(0, 11) + "...";
		}
		// 设置字体为加粗
		TextPaint paint =  topTitleTxt.getPaint();  
		paint.setFakeBoldText(true); 
		
		topTitleTxt.setText(title);
		topTitleTxt.setVisibility(View.VISIBLE);
				
	}
	
	protected void setTopTitle(String title) {
		if (title == null) {
			return;
		}
		if (title.length() > 12) {
			title = title.substring(0, 11) + "...";
		}
		topTitleTxt.setText(title);
		topTitleTxt.setVisibility(View.VISIBLE);
	}

	protected void hideTopTitle() {
		topTitleTxt.setVisibility(View.GONE);
	}

	protected void showContactTopBar() {
		topContactFrame.setVisibility(View.VISIBLE);
		topContactTitle.setVisibility(View.VISIBLE);
	}

	protected void setTopLeftButton(int resID) {
		if (resID <= 0) {
			return;
		}

		topLeftBtn.setImageResource(resID);
		topLeftBtn.setVisibility(View.VISIBLE);
	}

    protected void setTopLeftButtonPadding(int l,int t,int r,int b) {
        topLeftBtn.setPadding(l, t, r, b);
    }

	protected void hideTopLeftButton() {
		topLeftBtn.setVisibility(View.GONE);
	}

	protected void setTopLeftText(String text) {
		if (null == text) {
			return;
		}
		topLetTitleTxt.setText(text);
		topLetTitleTxt.setVisibility(View.VISIBLE);
	}

	protected void setTopRightText(String text) {
		if (null == text) {
			return;
		}
		topRightTitleTxt.setText(text);
		topRightTitleTxt.setVisibility(View.VISIBLE);
	}

	/**
	 * 设置顶右边的按钮
	 * @param resID
	 */
	protected void setTopRightButton(int resID) {
		if (resID <= 0) {
			return;
		}

		topRightBtn.setImageResource(resID);
		topRightBtn.setVisibility(View.VISIBLE);
		topRightBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				AddPopWindow addPopWindow = new AddPopWindow(getActivity());
				addPopWindow.showPopupWindow(topRightBtn);
			}
		});
	}

	protected void hideTopRightButton() {
		topRightBtn.setVisibility(View.GONE);
	}

	protected void setTopBar(int resID) {
		if (resID <= 0) {
			return;
		}
		topBar.setBackgroundResource(resID);
	}

    protected void hideTopBar()
    {
        topBar.setVisibility(View.GONE);
        LinearLayout.LayoutParams linearParams =(LinearLayout.LayoutParams) topContactFrame.getLayoutParams();
        linearParams.height = ScreenTools.instance(getActivity()).dip2px(45);
        topContactFrame.setLayoutParams(linearParams);
        topContactFrame.setPadding(0, ScreenTools.instance(getActivity()).dip2px(10), 0, 0);
    }

	/**
	 * 显示搜索框
	 */
	protected void showTopSearchBar() {
		topSearchEdt.setVisibility(View.VISIBLE);
	}

	protected void hideTopSearchBar() {
		topSearchEdt.setVisibility(View.GONE);
	}

	/**
	 * 显示搜索布局
	 */
	protected void showSearchFrameLayout(){
		searchFrameLayout.setVisibility(View.VISIBLE);
        /**还是以前的页面，没有看psd是否改过*/
        searchFrameLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                showSearchView();
            }
        });
        //下面的历史代码
        //tryHandleSearchAction(action);
	}

	protected abstract void initHandler();

	@Override
	public void onActivityCreated(Bundle bundle) {
		logger.d("Fragment onActivityCreate:" + getClass().getName());
		super.onActivityCreated(bundle);
	}

	public void NoGWho(){
		String sign=GesturespasswordSp.get(getActivity(),GesturespasswordSp.getNUM(),"");
		if ("".equals(sign)||sign==null){
			Num = false;
		}else{
			if (sign.trim().length()==6){
				Num = true;
			}else
				Num = false;
		}
		if (IMApplication.getInstance().getLockPatternUtils().savedPatternExists()){
			Ges = true;
		}else
			Ges = false;

		if (Num||Ges) {
			if (IMApplication.getInstance().isActive) {
				IMApplication.getInstance().isActive = false;
				if (Num) {
					startActivity(new Intent(getActivity(), DigitalCodeActivity.class));
				} else if (Ges) {
					startActivity(new Intent(getActivity(), UnlockGesturePasswordActivity.class));
				}
			}
		}
		IMApplication.getInstance().isActive = false;
	}

	public void NoGWho1(){
		String sign=GesturespasswordSp.get(getActivity(),GesturespasswordSp.getNUM(),"");
		if ("".equals(sign)||sign==null){
			Num = false;
		}else{
			if (sign.trim().length()==6){
				Num = true;
			}else
				Num = false;
		}
		if (IMApplication.getInstance().getLockPatternUtils().savedPatternExists()){
			Ges = true;
		}else
			Ges = false;
		if (Num||Ges) {
			if (Num) {
				startActivity(new Intent(getActivity(), DigitalCodeActivity.class));
			} else if (Ges) {
				startActivity(new Intent(getActivity(), UnlockGesturePasswordActivity.class));
			}
		}
	}

	public BroadcastReceiver testReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			switch (intent.getAction()){
				case "android.intent.action.SCREEN_OFF":
				case "android.intent.action.SCREEN_SCREEN_ON":
				case "android.intent.action.USER_PRESENT":
					if (!IMApplication.getInstance().isActive) {
						NoGWho1();
					}
					break;
			}
		}
	};

	@Override
	public void onStart() {
		super.onStart();
		final IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_SCREEN_OFF);
		filter.addAction(Intent.ACTION_SCREEN_ON);
		filter.addAction(Intent.ACTION_USER_PRESENT);
		getActivity().registerReceiver(testReceiver, filter);
	}

	@Override
	public void onStop() {
		super.onStop();
		if (!IMApplication.getInstance().isAppOnForeground()) {
			IMApplication.getInstance().isActive = true;
		}
	}

	@Override
	public void onResume() {
		NoGWho();
		super.onResume();
	}

	@Override
	public void onPause() {
		super.onPause();
	}
	@Override
	public void onDestroy(){
		super.onDestroy();
		getActivity().unregisterReceiver(testReceiver);
	}

	protected void initSearch() {
		setTopRightButton(R.drawable.tt_top_search);
		topRightBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				showSearchView();
			}
		});
	}

	public void showSearchView() {
		startActivity(new Intent(getActivity(), SearchActivity.class));
	}
	
	protected void onSearchDataReady() {
		initSearch();
	}

	/**
	 * 判断是否为平板
	 *
	 * @return
	 */
	private boolean isPad() {
		WindowManager wm = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
		Display display = wm.getDefaultDisplay();
		// 屏幕宽度
		float screenWidth = display.getWidth();
		// 屏幕高度
		float screenHeight = display.getHeight();
		DisplayMetrics dm = new DisplayMetrics();
		display.getMetrics(dm);
		double x = Math.pow(dm.widthPixels / dm.xdpi, 2);
		double y = Math.pow(dm.heightPixels / dm.ydpi, 2);
		// 屏幕尺寸
		double screenInches = Math.sqrt(x + y);
		// 大于6尺寸则为Pad
		if (screenInches >= 6.0) {
			return true;
		}
		return false;
	}
}
